package cn.cboard.gateway;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author 
 *
 * 
 * DAO  for issuing queries. 
 */
public class DAO {

    public ResultSetConverter defaultConverter;

    /**
     * Construct a basic DAO with the default converter
     */
    public DAO() {
        this.defaultConverter = new MapConverter();
    }

    /**
     * Construct a basic DAO with the supplied
     * ResultSet to Object converter
     */
    public DAO(ResultSetConverter converter) {
        this.defaultConverter = converter;
    }

   

    /**
     * Issue a query to the database. Convert each row in the result set
     * using the converter and return the entire list.
     * 
     * Pass row limit as -1 if you do not wish to limit the rows, otherwise the
     * number of rows will be limited to your supplied limit
     * 
     * If the converter is null, the default converter will be used
     * 
     * Pass fetch size as -1 if you do not wish to set the fetch hints 
     * 
     * Use SQLUtil to help construct your SQL
     */
    public List executeQuery(String rawsql, int rowLimit, int fetchSize, ResultSetConverter converter, Object[] params) throws DAOException {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        ResultSetConverter converterToUse = (converter == null) ? defaultConverter : converter;
        List results = new ArrayList();


        try {
            // get a connection
            conn = DAOUtil.getConnection();

            // prepare a stmt
            stmt = conn.prepareStatement(rawsql);

            // substitute stmt params
            if (params != null) {
                DAOUtil.substitute(stmt, params);
            }

            // if a limit is set use it
            if (rowLimit > 0) {
                stmt.setMaxRows(rowLimit);
            }

            //if the fetch size > 0 use it 
            if (fetchSize > 0) {
                stmt.setFetchSize(fetchSize);
            }

            rs = stmt.executeQuery();

            // Iterate over result set and convert to strongly typed objects
            // and place in a list to return to caller
            while (rs.next()) {
                Object row = converterToUse.toObject(rs);
                if (row != null) {       
                    results.add(row);
                }
            } // end while

            return results;
        } catch (SQLException e) {
            throw new DAOException(e);
        } finally {
            // Allways close everything regardless of what happened!!!!
            DAOUtil.close(conn, stmt, rs);
        }

    }
}
